package com.evan.review.ipc;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Process;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.evan.review.R;

/**
 * Binder通信示例
 * 演示如何使用自定义Binder实现跨进程通信
 */
public class BinderDemoActivity extends AppCompatActivity {

    private TextView tvServiceStatus;
    private TextView tvCounter;
    private EditText etInitialValue;
    private Button btnConnect, btnDisconnect;
    private Button btnIncrement, btnDecrement, btnReset;

    // Binder服务接口
    private CounterService.CounterBinder counterBinder;
    private boolean isBound = false;

    // 服务连接回调
    private final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 获取服务Binder对象
            counterBinder = (CounterService.CounterBinder) service;
            isBound = true;
            updateServiceStatus(true);
            updateCounterDisplay();
            Toast.makeText(BinderDemoActivity.this, "服务已连接", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // 服务意外断开
            counterBinder = null;
            isBound = false;
            updateServiceStatus(false);
            Toast.makeText(BinderDemoActivity.this, "服务已断开", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_binder_demo);

        // 初始化视图
        initViews();
        // 设置监听器
        setupListeners();
    }

    private void initViews() {
        tvServiceStatus = findViewById(R.id.tv_service_status);
        tvCounter = findViewById(R.id.tv_counter);
        etInitialValue = findViewById(R.id.et_initial_value);
        btnConnect = findViewById(R.id.btn_connect);
        btnDisconnect = findViewById(R.id.btn_disconnect);
        btnIncrement = findViewById(R.id.btn_increment);
        btnDecrement = findViewById(R.id.btn_decrement);
        btnReset = findViewById(R.id.btn_reset);

        updateServiceStatus(false);
    }

    private void setupListeners() {
        // 连接服务
        btnConnect.setOnClickListener(v -> {
            String initialValueStr = etInitialValue.getText().toString();
            int initialValue = 0;
            if (!initialValueStr.isEmpty()) {
                try {
                    initialValue = Integer.parseInt(initialValueStr);
                } catch (NumberFormatException e) {
                    Toast.makeText(this, "请输入有效的数字", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            bindCounterService(initialValue);
        });

        // 断开服务
        btnDisconnect.setOnClickListener(v -> unbindCounterService());

        // 增加计数
        btnIncrement.setOnClickListener(v -> {
            if (isBound && counterBinder != null) {
                counterBinder.increment();
                updateCounterDisplay();
            } else {
                Toast.makeText(this, "服务未连接", Toast.LENGTH_SHORT).show();
            }
        });

        // 减少计数
        btnDecrement.setOnClickListener(v -> {
            if (isBound && counterBinder != null) {
                counterBinder.decrement();
                updateCounterDisplay();
            } else {
                Toast.makeText(this, "服务未连接", Toast.LENGTH_SHORT).show();
            }
        });

        // 重置计数
        btnReset.setOnClickListener(v -> {
            if (isBound && counterBinder != null) {
                String initialValueStr = etInitialValue.getText().toString();
                int initialValue = 0;
                if (!initialValueStr.isEmpty()) {
                    try {
                        initialValue = Integer.parseInt(initialValueStr);
                    } catch (NumberFormatException e) {
                        Toast.makeText(this, "请输入有效的数字", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                counterBinder.resetCounter(initialValue);
                updateCounterDisplay();
            } else {
                Toast.makeText(this, "服务未连接", Toast.LENGTH_SHORT).show();
            }
        });

        // Binder介绍
        findViewById(R.id.btn_binder_intro).setOnClickListener(v -> showBinderIntroduction());
    }

    // 绑定计数器服务
    private void bindCounterService(int initialValue) {
        Intent intent = new Intent(this, CounterService.class);
        intent.putExtra("initial_value", initialValue);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    // 解绑计数器服务
    private void unbindCounterService() {
        if (isBound) {
            unbindService(serviceConnection);
            counterBinder = null;
            isBound = false;
            updateServiceStatus(false);
        }
    }

    // 更新计数器显示
    private void updateCounterDisplay() {
        if (isBound && counterBinder != null) {
            int count = counterBinder.getCount();
            String clientPid = String.valueOf(Process.myPid());
            String serverPid = String.valueOf(counterBinder.getServicePid());
            
            tvCounter.setText("当前计数: " + count + "\n" +
                    "客户端进程ID: " + clientPid + "\n" +
                    "服务端进程ID: " + serverPid);
        } else {
            tvCounter.setText("服务未连接");
        }
    }

    // 更新服务状态显示
    private void updateServiceStatus(boolean connected) {
        tvServiceStatus.setText("服务状态: " + (connected ? "已连接" : "未连接"));
        
        // 更新按钮状态
        btnConnect.setEnabled(!connected);
        btnDisconnect.setEnabled(connected);
        btnIncrement.setEnabled(connected);
        btnDecrement.setEnabled(connected);
        btnReset.setEnabled(connected);
    }

    // 显示Binder介绍对话框
    private void showBinderIntroduction() {
        new androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle("Binder通信介绍")
                .setMessage("Binder是Android的一种进程间通信机制，也是Android系统服务的基础。\n\n" +
                        "Binder特性：\n" +
                        "1. 性能高效：只需一次数据拷贝\n" +
                        "2. 安全性好：具有身份验证功能\n" +
                        "3. 实现简单：对开发者透明\n\n" +
                        "本示例中的跨进程通信：\n" +
                        "- 当客户端与服务在同一进程中，会直接调用Binder对象的方法\n" +
                        "- 当客户端与服务在不同进程中，Binder会自动处理跨进程方法调用\n\n" +
                        "Binder是Android其他IPC机制的基础，如AIDL、Messenger等都基于Binder实现")
                .setPositiveButton("了解", null)
                .show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 确保在Activity销毁时解绑服务
        unbindCounterService();
    }
} 